<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item label="部门名称" label-width="100px" prop="name">
        <el-input v-model="form.name" autocomplete="off" placeholder="2-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" label-width="100px" prop="code">
        <el-input v-model="form.code" autocomplete="off" placeholder="2-50个字符" />
      </el-form-item>
      <el-form-item label="部门负责人" label-width="100px" prop="manager">
        <el-select v-model="form.manager" placeholder="请选择" value>
          <el-option v-for="item in employees" :key="item.id" :label="item.username" :value="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" label-width="100px" prop="introduce">
        <el-input v-model="form.introduce" autocomplete="off" placeholder="2-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="onCancel">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </div>
  </div>
</template>

<script>
import { getEmployeeSimple, addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
export default {
  props: {
    isEdit: {
      type: Boolean,
      required: true
    },
    id: {
      type: String,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    // 部门名称的自定义校验
    const checkName = (rule, value, callback) => {
      let nameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      console.log('名称数组', nameList)
      if (this.isEdit) {
        const item = this.originList.find(item => item.id === this.id)
        const pid = item.pid
        nameList = this.originList.filter(item => item.pid === pid && item.id !== this.id).map(item => item.name)
      }
      nameList.includes(value) ? callback(new Error(value + '已被占用')) : callback()
    }
    // 部门编码的自定义校验
    const checkCode = (rule, value, callback) => {
      let codeList = this.originList.map(item => item.code)
      console.log('编码数组', codeList)
      if (this.isEdit) {
        codeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      codeList.includes(value) ? callback(new Error(value + '已被占用')) : callback()
    }
    return {
      form: {
        name: '', // 部门名称
        introduce: '', // 部门介绍
        manager: '', // 部门管理者
        code: '' // 部门编码
      },
      employees: [],
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 2, max: 50, message: '部门名称为2~50个字符', trigger: 'blur' },
          { validator: checkName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 2, max: 50, message: '部门编码为2~50个字符', trigger: 'blur' },
          { validator: checkCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门管理者不能为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 2, max: 50, message: '部门介绍为2~300个字符', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    // 'id': {
    //   handler: function(newVal, oldVal) {
    //     console.log('id变了！ 新值：', newVal, '旧值', oldVal)
    //     // 重发请求获取详情
    //     this.loadDepartmentDetailById()
    //   },
    //   immediate: true
    // }
    'id': function(newVal, oldVal) {
      console.log('id变了! 新值：', newVal, '旧值', oldVal)
      // 重发请求获取详情
      this.loadDetail()
    }
  },
  created() {
    this.loadEmployee()
    if (this.isEdit) {
      this.loadDetail()
    }
  },
  methods: {
    async loadEmployee() {
      const res = await getEmployeeSimple()
      this.employees = res.data
    },
    async loadDetail() {
      if (this.isEdit) {
        // alert('现在是编辑，要去获取详情')
        const res = await getDepartDetail(this.id)
        console.log('现在是编辑，要去获取详情', res)
        this.form = res.data
      }
    },
    async doAdd() {
      const res = await addDepartments({ ...this.form, pid: this.id })
      console.log(res)
      this.$emit('success')
    },
    async doEdit() {
      try {
        await updateDepartments(this.form)
        this.$message({ type: 'success', message: '修改成功' })
        this.$emit('success')
      } catch (err) {
        console.log(err)
        this.$message({ type: 'error', message: err })
      }
    },
    onSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.isEdit ? this.doEdit() : this.doAdd()
        }
      })
    },
    onCancel() {
      this.$emit('close')
    }
  }

}
</script>

